<template>
  <div class="good-cate">

    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片内容 -->
    <el-card>

      <!-- 按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCateDiaglose">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 展示内容 -->
      <tree-table :data="categoriesList" :columns="categoriesColumns" :selection-type="false" :expand-type="false"
        :show-index="true" index-text="#" border style="margin-top: 15px;">

        <!-- 是否有效模板 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-circle-check" v-if="!scope.row.cat_deleted" style="color:lightgreen"></i>
          <i class="el-icon-circle-close" v-if="scope.row.cat_deleted" style="color: red;"></i>
        </template>

        <!-- 等级模板 -->
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0" size="mini">一级</el-tag>
          <el-tag type="success" v-if="scope.row.cat_level === 1" size="mini">二级</el-tag>
          <el-tag type="warning" v-if="scope.row.cat_level === 2" size="mini">三级</el-tag>
        </template>

        <!-- 操作模板 -->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" class="el-icon-edit" size="mini" @click="editCateDiaglose(scope.row)">编辑</el-button>
          <el-button type="danger" class="el-icon-delete" size="mini"
            @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>

      <!-- 页脚 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage" :page-sizes="[1, 3, 5, 15]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

      <!-- 添加分类弹窗 -->
      <el-dialog title="提示" :visible.sync="isShowAddCate" width="50%" @close="addCateDiagloseClose">

        <!-- 表单 -->
        <el-form ref="addCateRef" :model="addCateList" :rules="addCateRules" label-width="100px">
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="addCateList.cat_name"></el-input>
          </el-form-item>

          <el-form-item label="父级分类：">
            <el-cascader v-model="cascaderSelected" :options="cascaderList" :props="cascaderProps" siz="mini" clearable
              @change="parentCateChange()"></el-cascader>
          </el-form-item>
        </el-form>

        <!-- 按钮 -->
        <span slot="footer">
          <el-button @click="isShowAddCate = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑分类 -->
      <el-dialog title="提示" :visible.sync="isShowEdite" width="50%">

        <!-- 表单区域 -->
        <el-form ref="editCateForm" :model="editList">
          <el-form-item label="分类名称">
            <el-input v-model="editList.cat_name"></el-input>
          </el-form-item>
        </el-form>

        <!-- 按钮 -->
        <span slot="footer">
          <el-button @click="isShowEdite = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      categoriesList: [],
      categoriesColumns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'level'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      queryInfo: {
        type: 3,
        pagenum: 1, // 当前页数
        pagesize: 5 // 当前页面数据条数
      },
      total: 0, // 类目总条数
      addCateList: { // 容纳用户添加分类的的信息,网络请求
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      isShowAddCate: false, // 添加用户弹窗
      isShowEdite: false,
      addCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      cascaderList: [// 用于联级选择器的数据,

      ],
      cascaderProps: { // 联级选择器的配置项
        label: 'cat_name',
        value: 'cat_pid',
        children: 'children',
        expandTrigger: 'hover'
        // checkStrictly: 'true'
      },
      cascaderSelected: [ // 联级选择器被选中的值
      ],

      selectedCate: { // 当前被选中的信息

      },

      editList: { // 修改分类后的信息
        cat_name: '',
        cat_id: Number
      }
    }
  },
  methods: {
    // 获取商品
    async getcategories () {
      const { data: res } = await this.$http.get('categories', { params: { pagenum: this.queryInfo.pagenum, pagesize: this.queryInfo.pagesize } })
      if (res.meta.status !== 200) return this.$message.error('获取商品列表失败')
      this.categoriesList = res.data.result
      this.total = res.data.total
    },

    // 处理页面每张数据数量变化
    handleSizeChange (newVal) {
      this.queryInfo.pagesize = newVal
      this.getcategories()
    },

    // 处理页数变化
    handleCurrentChange (newVal) {
      this.queryInfo.pagenum = newVal
      this.getcategories()
    },

    // 添加分类弹窗
    async addCateDiaglose () {
      this.isShowAddCate = true
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error('网络请求失败')
      this.cascaderList = res.data
    },

    parentCateChange () { // 当选中的父级分类发生变化时触发
      if (this.cascaderSelected.length > 0) {
        this.addCateList.cat_pid = this.cascaderList[this.cascaderList.length - 1]
        this.addCateList.cat_level = this.cascaderList.length
      } else {
        this.addCateList.cat_pid = 0
        this.addCateList.cat_level = 0
      }
    },

    addCate () { // 用户提交分类分类商品时触发
      this.$refs.addCateRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必须要信息')
        const { data: res } = await this.$http.post('categories', this.addCateList)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.cascaderSelected = []
        this.addCateList.cat_pid = 0
        this.addCateList.cat_level = 0
        this.isShowAddCate = false
      })
    },
    // 弹窗框关闭触发
    addCateDiagloseClose () {
      this.$refs.addCateRef.resetFields()
    },

    // 打开编辑弹窗
    editCateDiaglose (cate) {
      this.isShowEdite = true
      this.selectedCate = cate
      this.editList.cat_name = this.selectedCate.cat_name
      this.editList.cat_id = this.selectedCate.cat_id
    },

    // 提交编辑好的内容
    editCate () {
      this.$refs.editCateForm.validate(async valid => {
        const { data: res } = await this.$http.put(`categories/${this.editList.cat_id}`, { cat_name: this.editList.cat_name })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.isShowEdite = false
        this.editList = {}
        this.getcategories()
      })
    },

    // 删除分类
    deleteCate (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getcategories()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  },
  created () {
    this.getcategories()
  }
}
</script>
<style lang="scss">
::v-deep .el-cascader-panel {
  max-height: 300px;
}

.el-cascader {
  width: 100%;
}
</style>
